import type { Module } from 'vuex'
import type { AppFuncTree, RootStateTypes } from '../interface'
import type AppFunc from '@jsjn/types/entity/AppFunc'
import type { RouteConfig } from '@jsjn/types/Route'
import { assignOwnProp } from '@jsjn/micro-core-utils/utils'
import { forParent } from '@jsjn/micro-core-micro-main/sendData'

const appFuncTree: Module<AppFuncTree, RootStateTypes> = {
    namespaced: true,
    state() {
        return {
            systemAppFuncTree: [],
            remoteRegisteredRoutes: [],
            registeredRoutes: [],
            routeConfigs: []
        }
    },
    mutations: {
        setSystemAppFuncTree(state, data: { sysData: AppFunc[]; refreshUserFuncTree: boolean }) {
            /**
             * uums 特例
             * 应用功能所有的树
             */
            state.systemAppFuncTree = data.sysData

            /**
             * uums 特例
             * 在修改应用功能模块的功能树时，要抛出数据到基座应用
             */
            forParent({ systemAppFuncTree: data })
        },
        setRemoteRegisteredRoutes(state, data: RouteConfig[]) {
            const currentState = JSON.stringify(state.remoteRegisteredRoutes)
            const nextState = JSON.stringify(data)
            if (currentState === nextState) return
            state.remoteRegisteredRoutes = data
        },
        setRegisteredRoutes(state, data: RouteConfig[]) {
            state.registeredRoutes = data
        },
        setRouteConfigs(state, data: RouteConfig[]) {
            pathClearBlurry(data)
            state.routeConfigs = data
        },
        // 全量赋值
        setAppFuncTreeStoreModule(state, data: AppFuncTree) {
            const currentState = JSON.stringify(state)
            const nextState = JSON.stringify(data)
            if (currentState === nextState) return
            assignOwnProp(state, data)
        }
    },
    actions: {}
}

export default appFuncTree

/**
 * 微应用的路由中，为了兼容嵌套应用，path 采用了模糊匹配模式
 * 即：abc/defg/:page*
 *
 * 模糊匹配的路由是不需要映射到菜单上的，所以，在设置 routeConfigs 要清理路径的模糊匹配
 * 注意：
 *  - routeConfigs 不需要
 *  - registeredRoutes 是需要的
 */
const pageBlurryKey = '/:page*'
function pathClearBlurry(routes: RouteConfig[]) {
    routes.forEach((route) => {
        if (!!route.children?.length) {
            pathClearBlurry(route.children)
        }

        if (route.path.includes(pageBlurryKey)) {
            route.path = route.path.replace(pageBlurryKey, '')
        }
    })
}
